const { query: dbQuery } = require('../config/database');
const { logger } = require('../utils/logger');

// 等级阈值（累计获得积分）
// lv1: 0-199 -> bronze, lv2: 200-799 -> silver, lv3: 800-1599 -> gold, lv4: 1600+ -> platinum
const LEVELS = [
  { code: 'lv1', name: 'bronze', min: 0, nextAt: 200 },
  { code: 'lv2', name: 'silver', min: 200, nextAt: 800 },
  { code: 'lv3', name: 'gold', min: 800, nextAt: 1600 },
  { code: 'lv4', name: 'platinum', min: 1600, nextAt: null }
];

function levelFromLifetime(points) {
  if (points >= 1600) return LEVELS[3];
  if (points >= 800) return LEVELS[2];
  if (points >= 200) return LEVELS[1];
  return LEVELS[0];
}

module.exports = {
  LEVELS,
  async evaluateAndUpdateUserLevel(userId) {
    try {
      // 计算累计获得积分：仅统计type='earn'的正向入账，排除被撤销/反向的记录
      const rows = await dbQuery(
        `SELECT COALESCE(SUM(points_change), 0) AS lifetime
         FROM points_history
         WHERE user_id = ? AND type = 'earn' AND status IN ('active','expired')`,
        [userId]
      );
      const lifetime = rows[0]?.lifetime || 0;
      const lvl = levelFromLifetime(lifetime);

      // 更新用户membership_level为客户端兼容命名
      await dbQuery(
        `UPDATE users SET membership_level = ?, updated_at = NOW() WHERE user_id = ?`,
        [lvl.name, userId]
      );

      return { lifetime, level: lvl };
    } catch (err) {
      logger.error('evaluateAndUpdateUserLevel failed:', err);
      throw err;
    }
  },

  getLevelByLifetime(points) {
    return levelFromLifetime(points);
  }
};